package com.music.activity;
//基类，activity共有的部分可写在基类，然后再继承实现

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

import com.music.utilbean.Contant;
import com.music.utilbean.DBhelper;

public abstract class MusicBaseActivity extends Activity {
	protected PlayService playService;
	private boolean isbound = false;
	protected MyMusicListFragment musicListFragment;
	protected NetBDMusicFragment  netBDMusicFragment;
	protected SharedPreferences   sp;//退出时保存状态
	protected DBhelper            helper;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		sp = getSharedPreferences(Contant.SP_NAME, Context.MODE_PRIVATE);
		helper = new DBhelper(getBaseContext(), "music.db", null, 5);

	}

	protected ServiceConnection serviceConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName arg0, IBinder arg1) {
			Log.i("connection", "service is connected");
			PlayService.PlayBinder playBinder = (PlayService.PlayBinder) arg1;
			playService = playBinder.getPlayService();
			playService.setMusicUpdateListener(musicUpdateListener);
			if (musicUpdateListener != null) {
				musicUpdateListener.onChange(playService.getCurrentPosition());
			}
		}

		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			Log.i("connection", "service is not connected");
			playService = null;
			isbound = false;
		}


	};

	//绑定服务
	public void bindplayService() {
		if (!isbound) {
			Intent intent = new Intent(this, PlayService.class);
			this.getApplicationContext().bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
			Log.i("bind", "服务绑定");//TabActivity的问题，bindservice要加getapplicationcontext
			isbound = true;
		}
	}

	//解除服务绑定
	public void unbindplayService() {
		if (isbound) {
			this.getApplicationContext().unbindService(serviceConnection);
			Log.i("unbind", "服务解绑");
			isbound = false;
		}
	}

	//实现接口的方法
	private PlayService.MusicUpdateListener musicUpdateListener = new PlayService.MusicUpdateListener() {
		@Override
		public void onPublish(int progress) {
			publish(progress);//更新进度条
		}

		@Override
		public void onChange(int position) {
			change(position);//改变歌曲
		}
	};

	public abstract void publish(int progress);

	public abstract void change(int position);
}
